package com.halflife.parameter.template;

import com.halflife.comeElectricity.basic.datadic.DataDic;
import com.halflife.comeElectricity.basic.datadic.DataDicRepository;
import com.halflife.comeElectricity.basic.datadic.DataDicType;
import com.halflife.comeElectricity.basic.datadic.DataDicTypeRepository;
import com.halflife.framework.converter.MapHandler;
import com.halflife.framework.domain.Page;
import com.halflife.framework.participant.user.UserView;
import com.halflife.framework.utils.ImageUploadUtil;
import com.halflife.parameter.SearchKeyWord;
import com.halflife.parameter.SearchKeyWordRepository;
import com.halflife.shiro.utils.ShiroUtil;
import com.sun.xml.internal.bind.v2.model.core.ID;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class TemplateAdminController {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private TemplateRepository templateRepository;
    @Resource
    private ParameterRepository parameterRepository;
    @Resource
    private DataDicRepository dataDicRepository;
    @Resource
    private DataDicTypeRepository dataDicTypeRepository;
    @Resource
    private SearchKeyWordRepository searchKeyWordRepository;

    @RequestMapping("front/index")
    public String index(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                        HttpServletRequest request, Model model) {
        this.setProps(model);
        return "index";
    }
    @RequestMapping("admin/parameters/index")
    public String adminIndex(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                        HttpServletRequest request, Model model) {
        this.setProps(model);
        return "index";
    }

    @RequestMapping("admin/parameters/my_index")
    public String myIndex(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                          HttpServletRequest request, Model model) {
        this.setProps(model);
        return "my_index";
    }
    @RequestMapping("front/parameters/summary_info")
    public String summary_info(Integer id,@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        UserView user = ShiroUtil.getUserView(request);
        Template template = new Template();
        if(id!=null){
            template = templateRepository.selectByPrimaryKey(id);
            Template logTemplate = new Template();
            logTemplate.setId(template.getId());
            logTemplate.setViewCount(template.getViewCount() == null ? 0 : (template.getViewCount() + 1));
            logTemplate.setLastViewerId(user.getId());
            logTemplate.setLastViewerPhoto(user.getProfilePhoto());
            logTemplate.setLastViewerName(user.getName());
            logTemplate.setLastViewTime(new Date());
            templateRepository.updateByPrimaryKeySelective(logTemplate);
        }
        if (StringUtils.isBlank(template.getImg())) {
            template.setImg("/static/images/img_01.png");
        }
        model.addAttribute("template", template);
        this.setProps(model);
        return "template/summary_info";
    }


    @RequestMapping("front/content_list")
    public String font_content_list(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        this.init_content_list(queryParam,page,model);
        return "template/front_content_list";
    }

    @RequestMapping("admin/parameters/content_list")
    public String content_list(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        UserView user = ShiroUtil.getUserView(request);
        queryParam.put("userViewId", user.getId());
        this.init_content_list(queryParam,page,model);
        return "template/content_list";
    }
    private void init_content_list(HashMap<String,Object> queryParam, Page page,Model model){
        StringBuilder sb = new StringBuilder();
        Map<String, Object> queryP = MapHandler.handleParamMap(queryParam,sb,(keyword)->{
            sb.append(" and( t.name like '%").append(keyword).append("%'");
            sb.append(" or t.photoType like '%").append(keyword).append("%'");
            sb.append(" or t.clientName like '%").append(keyword).append("%'");
            sb.append(" or t.productCategory like '%").append(keyword).append("%'");
            sb.append(" or t.photoStyle like '%").append(keyword).append("%'");
            sb.append(" or t.sceneStyle like '%").append(keyword).append("%'");
            sb.append(" or t.lightingStyle like '%").append(keyword).append("%'");
            sb.append(" or t.creator like '%").append(keyword).append("%'");
            sb.append(")");

            int updateRows = searchKeyWordRepository.updateAny("update t_parameter_searchKeyWord t set t.ordinal = (ifnull(t.ordinal,0)+1) where t.keywords='"+keyword.trim().toLowerCase()+"'");
            if (updateRows < 1) {
                SearchKeyWord searchKeyWord = new SearchKeyWord();
                searchKeyWord.setKeyWords(keyword.trim().toLowerCase());
                searchKeyWord.setOrdinal(0);
                searchKeyWord.setSearchWords(keyword);
                searchKeyWordRepository.insert(searchKeyWord);
            }
        });
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryP);
//        queryP.put("valid", true);
        queryP.put("endSql", sb.toString());
        int totalCount = templateRepository.selectCount(queryP);
        List<Template> list = templateRepository.selectListByPage(queryP);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
    }
    @RequestMapping(value = "admin/parameters/mainImgeUpload", method = RequestMethod.POST)
    public ResponseEntity<Map<String,Object>> mainImgUpload(HttpServletRequest request, HttpServletResponse response,
                                                             Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            MultipartFile file = multipartRequest.getFile("uploadFile");
            String fileName = ImageUploadUtil.upload(request, file);
//            String imageContextPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String imageContextPath = "";
            //拼接回传地址
            imageContextPath = "/fileUpload/" + sdf.format(new Date()) + "/" + fileName;

            map.put("SUCESS", true);
            map.put("DATA",imageContextPath);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
    }
    @RequestMapping(value = "admin/parameters/mainImgeUpload1", method = RequestMethod.POST)
    public ResponseEntity<Map<String,Object>> mainImgUpload1(Integer id,HttpServletRequest request, HttpServletResponse response,
                                                             Model model) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String base64String=request.getParameter("imageData");//获取前端传来的base64码

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = ImageUploadUtil.upload1(request, base64String);
            String imageContextPath = "";
            //拼接回传地址
            imageContextPath = "/fileUpload/" + sdf.format(new Date()) + "/" + fileName;

            map.put("SUCESS", true);
            map.put("DATA",imageContextPath);
            Template template = new Template();
            template.setId(id);
            template.setImg(imageContextPath);
            templateRepository.updateByPrimaryKeySelective(template);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.toString(),e);
            return new ResponseEntity<Map<String,Object>>(map, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<Map<String,Object>>(map, HttpStatus.OK);
    }
    private void setProps(Model model){
        Map<String, Object> params = new HashMap<>();
        params.put("valid", true);
        params.put("dataDicTypeId", 8);
        List<DataDic>  photoStyles = dataDicRepository.selectAll(params);
        model.addAttribute("photoStyles", photoStyles);
        params.put("dataDicTypeId", 7);
        List<DataDic>  lightingStyles = dataDicRepository.selectAll(params);
        model.addAttribute("lightingStyles", lightingStyles);

        params.put("dataDicTypeId", 6);
        List<DataDic>  sceneStyles = dataDicRepository.selectAll(params);
        model.addAttribute("sceneStyles", sceneStyles);
        params.put("dataDicTypeId", 3);
        List<DataDic>  photoTypes = dataDicRepository.selectAll(params);
        model.addAttribute("photoTypes", photoTypes);
    }
    @RequestMapping("admin/parameters/summary_edit")
    public String summary_edit(Integer id,@RequestParam(required = false) HashMap<String,Object> queryParam,String option, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        Template template = new Template();
        if(id!=null){
            template = templateRepository.selectByPrimaryKey(id);
        }
        if (StringUtils.isBlank(template.getImg())) {
            template.setImg("/static/images/img_01.png");
        }
        model.addAttribute("template", template);
        model.addAttribute("option", option);
        this.setProps(model);
        return "template/summary_edit";
    }
    @RequestMapping("admin/parameters/list")
    public String gotoParamegersList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        queryParam.put("valid", true);
        Map<String, Object> queryP = new HashMap<>();
        queryP.putAll(queryParam);

        StringBuilder endSql = new StringBuilder();
        endSql.append(" 1=1 ");
        if (queryParam.containsKey("lightCount")) {
            int lightCount = Integer.valueOf((String) queryParam.get("lightCount"));
            queryParam.remove("lightCount");
            switch (lightCount) {

                case 1:
                    endSql.append(" and t.lightCount between 1 and 5");
                    break;
                case 2:
                    endSql.append(" and t.lightCount between 6 and 10");
                    break;
                case 3:
                    endSql.append(" and t.lightCount > 10");
                    break;
            }
        }
        if (queryParam.containsKey("propsCount")) {

            int propsCount = Integer.valueOf((String) queryParam.get("propsCount"));
            queryParam.remove("propsCount");
            switch (propsCount) {

                case 1:
                    endSql.append(" and t.propsCount =0");
                    break;
                case 2:
                    endSql.append(" and t.propsCount >0");
                    break;
            }
        }
        if (queryParam.containsKey("beginDate")) {
            endSql.append(" and t.createDate >= str_to_date('").append(queryParam.get("beginDate")).append("','%m/%d/%Y')");
        }
        if (queryParam.containsKey("endDate")) {
            endSql.append(" and t.createDate <= str_to_date('").append(queryParam.get("endDate")).append("','%m/%d/%Y')");
        }
        queryParam.put("endSql", endSql);
        int totalCount = templateRepository.selectCount(queryParam);
        List<Template> list = templateRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        Map<String, Object> params = new HashMap<>();
        params.put("valid", true);
        params.put("dataDicTypeId", 8);
        List<DataDic>  photoStyles = dataDicRepository.selectAll(params);
        model.addAttribute("photoStyles", photoStyles);
        params.put("dataDicTypeId", 7);
        List<DataDic>  lightingStyles = dataDicRepository.selectAll(params);
        model.addAttribute("lightingStyles", lightingStyles);

        params.put("dataDicTypeId", 6);
        List<DataDic>  sceneStyles = dataDicRepository.selectAll(params);
        model.addAttribute("sceneStyles", sceneStyles);
        params.put("dataDicTypeId", 3);
        List<DataDic>  photoTypes = dataDicRepository.selectAll(params);
        model.addAttribute("photoTypes", photoTypes);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",queryP);
        return "template/parameters";
    }
    @RequestMapping("admin/template/list")
    public String gotoList(@RequestParam(required = false) HashMap<String,Object> queryParam, Page page, HttpServletResponse response,
                           HttpServletRequest request, Model model) {
        MapHandler.handleMap(queryParam);
        if (page == null) {
            page = new Page();
        }
        page.setQueryParam(queryParam);
        int totalCount = templateRepository.selectCount(queryParam);
        List<Template> list = templateRepository.selectListByPage(queryParam);
        page.setTotalCount(totalCount);
        page.setMode(model);
        model.addAttribute("list",list);
        model.addAttribute("queryParam",queryParam);
        return "template/list";
    }

    @RequestMapping("admin/template/operate")
    public String gotoOperate(Integer id,HttpServletResponse response,
                               HttpServletRequest request, Model model) {
        Template template = new Template();
        if(id!=null){
            template = templateRepository.selectByPrimaryKey(id);
        }

        Map<String, Object> params = new HashMap<>();
        params.put("dataDicTypeId", 8);
        List<DataDic>  photoStyles = dataDicRepository.selectAll(params);
        model.addAttribute("photoStyles", photoStyles);
        params.put("dataDicTypeId", 7);
        List<DataDic>  lightingStyles = dataDicRepository.selectAll(params);
        model.addAttribute("lightingStyles", lightingStyles);

        params.put("dataDicTypeId", 6);
        List<DataDic>  sceneStyles = dataDicRepository.selectAll(params);
        model.addAttribute("sceneStyles", sceneStyles);
        params.put("dataDicTypeId", 5);
        List<DataDic>  productCategorys = dataDicRepository.selectAll(params);
        model.addAttribute("productCategorys", productCategorys);
        params.put("dataDicTypeId", 4);
        List<DataDic>  clientNames = dataDicRepository.selectAll(params);
        model.addAttribute("clientNames", clientNames);
        params.put("dataDicTypeId", 3);
        List<DataDic>  photoTypes = dataDicRepository.selectAll(params);
        model.addAttribute("photoTypes", photoTypes);

        model.addAttribute("template",template);
        return "template/operate";
    }

    @PostMapping("admin/template/save")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity save(Template template, HttpServletRequest request,
                              HttpServletResponse response, Model model) {
        try {
            int countView = 0;
            if(StringUtils.isNotBlank(template.getImg1())){
                countView++;
            }
            if(StringUtils.isNotBlank(template.getImg2())){
                countView++;
            }
            if(StringUtils.isNotBlank(template.getImg3())){
                countView++;
            }
            if(StringUtils.isNotBlank(template.getImg4())){
                countView++;
            }
            if(StringUtils.isNotBlank(template.getImg5())){
                countView++;
            }
            if (countView > 2) {
                countView = countView-2;
            }else{
                countView = 0;
            }
            template.setPageCount(countView);
            if(template.getId()!=null){
//                SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                template.setModifyDate(new Date());
                templateRepository.updateByPrimaryKeySelective(template);

            }else {
                template.init();
                UserView user = ShiroUtil.getUserView(request);
                template.setUserViewId(user.getId());
                template.setValid(true);
                template.setCreator(user.getUserName());
                Integer a = templateRepository.insert(template);
            }

        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(template.getId(), HttpStatus.OK);
    }

    @DeleteMapping("admin/template/delete")
    public ResponseEntity setRiderState(Integer id, Integer state) {
        try {
            Template template = new Template();
            template.setId(id);
            template.setValid(Boolean.FALSE);
            templateRepository.updateByPrimaryKeySelective(template);
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }

    @RequestMapping("admin/template/duplicate")
    public ResponseEntity duplicate(Integer id, Integer state,HttpServletRequest request,HttpServletResponse response) {
        try {
            Template template = templateRepository.selectByPrimaryKey(id);
            template.setId(null);
            UserView user = ShiroUtil.getUserView(request);
            template.setCreator(user.getUserName());
            template.setUserViewId(user.getId());
            template.setCreateDate(new Date());
            template.setModifyDate(null);
            template.setLastViewTime(null);
            template.setViewCount(1);
            template.setLastViewerName(null);
            template.setLastViewerId(null);
            template.setLastViewerPhoto(null);
            templateRepository.insert(template);
            Map<String, Object> param = new HashMap<>();
            param.put("templateId", id);
            List<Parameter> parameters = parameterRepository.selectAll(param);
            for (Parameter p : parameters) {
                p.setId(null);
                p.setTemplateId(template.getId());
                parameterRepository.insert(p);
            }
        } catch (Exception ex) {
            log.error(ex.toString(),ex);
            return new ResponseEntity(1, HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity(0, HttpStatus.OK);
    }
}
